package com.ruoyi.ams.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.ams.domain.AmsOwnUserAssetAuthority;
import com.ruoyi.ams.domain.vo.ApplyHistoryInifo;
import com.ruoyi.ams.domain.vo.ApplyUnlockAuthVo;
import com.ruoyi.ams.domain.vo.OwnUserAssetAuthorityIdAddVo;
import com.ruoyi.ams.domain.vo.OwnUserAssetAuthorityIdEditVo;
import com.ruoyi.ams.service.IAmsOwnAssetService;
import com.ruoyi.ams.service.IAmsOwnUserAssetAuthorityService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.AmsOwnAsset;
import com.ruoyi.common.core.domain.vo.UserDeptName;
import com.ruoyi.common.core.utils.SecurityUtils;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.rabbitmq.constant.NotifyConstants;
import com.ruoyi.common.rabbitmq.constant.RabbitmqConstants;
import com.ruoyi.common.rabbitmq.domain.SmsNotifyTemplate;
import com.ruoyi.common.rabbitmq.utils.NotifyUtils;
import com.ruoyi.security.annotation.PreAuthorize;
import com.ruoyi.system.controller.SysUserController;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * 物联网资产设备用户权限信息Controller
 *
 * @author yfkj
 * @date 2021-10-15
 */
@RestController
@RequestMapping("/ams/AmsOwnUserAssetAuthority")
public class AmsOwnUserAssetAuthorityController extends BaseController {
    @Autowired
    private IAmsOwnUserAssetAuthorityService amsOwnUserAssetAuthorityService;

    @Autowired
    private IAmsOwnAssetService amsOwnAssetService;

    @Autowired
    RabbitTemplate rabbitTemplate;

//    @Autowired
//    RemoteUserService remoteUserService;
    @Autowired
    private SysUserController userController;

    /**
     * 查询物联网资产设备用户权限信息列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AmsOwnUserAssetAuthority:list")
    @GetMapping("/list")
    @ApiOperation("物联网用户资产权限列表查询")
    public TableDataInfo list(AmsOwnUserAssetAuthority amsOwnUserAssetAuthority){
        startPage();
        List<AmsOwnUserAssetAuthority> list = amsOwnUserAssetAuthorityService.selectAmsOwnUserAssetAuthorityList(amsOwnUserAssetAuthority);
        return getDataTable(list);
    }

    /**
     * 导出物联网资产设备用户权限信息列表
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AmsOwnUserAssetAuthority:export")
    @Log(title = "物联网资产设备用户权限信息", businessType = BusinessType.EXPORT)
    @PostMapping(value="/export", produces = "application/octet-stream")
    public void export(HttpServletResponse response, AmsOwnUserAssetAuthority amsOwnUserAssetAuthority) throws IOException {
        List<AmsOwnUserAssetAuthority> list = amsOwnUserAssetAuthorityService.selectAmsOwnUserAssetAuthorityList(amsOwnUserAssetAuthority);
        ExcelUtil<AmsOwnUserAssetAuthority> util = new ExcelUtil<AmsOwnUserAssetAuthority>(AmsOwnUserAssetAuthority.class);
        util.exportExcel(response, list, "物联网资产设备用户权限信息数据");
    }

    /**
     * 获取物联网资产设备用户权限信息详细信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AmsOwnUserAssetAuthority:query")
    @GetMapping(value = "/info")
    @ApiOperation("物联网用户资产权限信息详情查询")
    public AjaxResult getInfo(@ApiParam(name = "ownUserAssetAuthorityId", value = "用户资产权限信息主键") Long ownUserAssetAuthorityId) {
        return AjaxResult.success(amsOwnUserAssetAuthorityService.selectAmsOwnUserAssetAuthorityByOwnUserAssetAuthorityId(ownUserAssetAuthorityId));
    }

    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AmsOwnUserAssetAuthority:add")
    @Log(title = "物联网资产设备用户权限信息", businessType = BusinessType.INSERT)
    @PostMapping("/addAmsOwnUserAssetAuthority")
    @ApiOperation("管理员用户资产权限添加")
    public AjaxResult add(@RequestBody OwnUserAssetAuthorityIdAddVo ownUserAssetAuthorityIdAddVo){
        if(ownUserAssetAuthorityIdAddVo.getAssetId() == null || ownUserAssetAuthorityIdAddVo.getUserId() == null
        || ownUserAssetAuthorityIdAddVo.getStartTime() == null || ownUserAssetAuthorityIdAddVo.getEndTime() == null){
                return AjaxResult.success("请完整添加参数");
        }
        List<AmsOwnUserAssetAuthority> authList = amsOwnUserAssetAuthorityService.list(new QueryWrapper<AmsOwnUserAssetAuthority>().
                eq(AmsOwnUserAssetAuthority.ASSET_ID, ownUserAssetAuthorityIdAddVo.getAssetId()).
                eq(AmsOwnUserAssetAuthority.USER_ID, ownUserAssetAuthorityIdAddVo.getUserId()).
                gt(AmsOwnUserAssetAuthority.END_TIME,System.currentTimeMillis()));
        if(authList.size() > 0){
            return AjaxResult.success("已经添加，请勿重复添加");
        }
        AmsOwnUserAssetAuthority authority = new AmsOwnUserAssetAuthority();
        BeanUtils.copyProperties(ownUserAssetAuthorityIdAddVo, authority);
        authority.setGrantUserId(SecurityUtils.getUserId());
        authority.setGrantType(2);
        authority.setStatus(1);
        authority.setCreateTime(System.currentTimeMillis());
        return toAjax(amsOwnUserAssetAuthorityService.save(authority));
    }

    /**
     * 修改物联网资产设备用户权限信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AmsOwnUserAssetAuthority:edit")
    @Log(title = "物联网资产设备用户权限信息", businessType = BusinessType.UPDATE)
    @PostMapping("/editAmsOwnUserAssetAuthority")
    @ApiOperation("管理员用户资产权限修改")
    public AjaxResult edit(@RequestBody OwnUserAssetAuthorityIdEditVo ownUserAssetAuthorityIdEditVo) {
        AmsOwnUserAssetAuthority authority = amsOwnUserAssetAuthorityService.getById(ownUserAssetAuthorityIdEditVo.getOwnUserAssetAuthorityId());
        BeanUtils.copyProperties(ownUserAssetAuthorityIdEditVo, authority);
        authority.setGrantUserId(SecurityUtils.getUserId());
        return toAjax(amsOwnUserAssetAuthorityService.updateAmsOwnUserAssetAuthority(authority));
    }


    @PostMapping("/userApplyUnlockAuth")
    @ApiOperation("用户申请开锁权限")
    public AjaxResult userApplyUnlockAuth(@RequestBody OwnUserAssetAuthorityIdAddVo ownUserAssetAuthorityIdAddVo) {
//        AmsOwnUserAssetAuthority authority =new AmsOwnUserAssetAuthority();
//        BeanUtils.copyProperties(ownUserAssetAuthorityIdAddVo,authority);
//        authority.setStatus(0);
//        return toAjax(amsOwnUserAssetAuthorityService.insertAmsOwnUserAssetAuthority(authority));
        System.out.println("用户申请开锁权限");
        System.out.println(ownUserAssetAuthorityIdAddVo);
        List<AmsOwnAsset> owns = amsOwnAssetService.list(new QueryWrapper<AmsOwnAsset>().eq("asset_id", ownUserAssetAuthorityIdAddVo.getAssetId()));
        List<AmsOwnUserAssetAuthority> list = amsOwnUserAssetAuthorityService.list(new QueryWrapper<AmsOwnUserAssetAuthority>().eq("asset_id", ownUserAssetAuthorityIdAddVo.getAssetId())
                .eq("user_id", SecurityUtils.getUserId()).ge("end_time",System.currentTimeMillis()));
        if(list != null && list.size() > 0){
            return AjaxResult.error("已申请，重复申请！");
        }
        if(owns != null && owns.size() > 0){
           /** SysUser sysUser = remoteUserService.getDeptManegerByDeptId(owns.get(0).getUseDeptId()).getData(); */
            AmsOwnUserAssetAuthority amsOwnUserAssetAuthority = new AmsOwnUserAssetAuthority();
            amsOwnUserAssetAuthority.setUserId(SecurityUtils.getUserId());
           /** amsOwnUserAssetAuthority.setUserId(23l); */
           /** amsOwnUserAssetAuthority.setGrantUserId(sysUser.getUserId());*/
            amsOwnUserAssetAuthority.setStatus(-1);
            amsOwnUserAssetAuthority.setEndTime(ownUserAssetAuthorityIdAddVo.getEndTime());
            amsOwnUserAssetAuthority.setStartTime(ownUserAssetAuthorityIdAddVo.getStartTime());
            amsOwnUserAssetAuthority.setGrantType(1);
            amsOwnUserAssetAuthority.setAssetId(ownUserAssetAuthorityIdAddVo.getAssetId());
            amsOwnUserAssetAuthority.setCreateTime(System.currentTimeMillis());
            amsOwnUserAssetAuthority.setDeptId(owns.get(0).getUseDeptId());
            if(ownUserAssetAuthorityIdAddVo.getRemark() == null){
                ownUserAssetAuthorityIdAddVo.setRemark("");
            }
            amsOwnUserAssetAuthority.setRemark(ownUserAssetAuthorityIdAddVo.getRemark());
            amsOwnUserAssetAuthorityService.save(amsOwnUserAssetAuthority);

            R<List<SysUser>> rSysUsers = userController.getDeptManegersByDeptId(owns.get(0).getUseDeptId());

            if(rSysUsers == null){
                List<SysUser> data = rSysUsers.getData();

                if(data != null && data.size() > 0){

                    Set<Object> map=new HashSet<>(data);
                    HashMap<String,String> paramMap = new HashMap<>();
                    paramMap.put("name", SecurityUtils.getUsername());
                    SmsNotifyTemplate smsNotifyTemplate = NotifyUtils.createIotSmsNotifyTemplate(map,paramMap, NotifyConstants.APPLY_UNLOCK_SMS);
                    rabbitTemplate.convertAndSend(RabbitmqConstants.EXCHANGE, RabbitmqConstants.SMS_ROUTINGKEY,smsNotifyTemplate);
                }

            }

            return toAjax(true);
        }else{
            return AjaxResult.error("资产信息出错！");
        }

    }

    @PostMapping("/userApplyAssetAuthority")
    @ApiOperation("用户申请资产权限")
    public AjaxResult userApplyAssetAuthority(@RequestBody OwnUserAssetAuthorityIdAddVo ownUserAssetAuthorityIdAddVo) {
        AmsOwnUserAssetAuthority authority = new AmsOwnUserAssetAuthority();
        BeanUtils.copyProperties(ownUserAssetAuthorityIdAddVo, authority);
        authority.setStatus(-1);
        return toAjax(amsOwnUserAssetAuthorityService.insertAmsOwnUserAssetAuthority(authority));
    }

    @PostMapping("/examineUserApplyAssetAuthority")
    @ApiOperation("管理员审核用户权限申请")
    public AjaxResult examineUserApplyAssetAuthority(@RequestBody OwnUserAssetAuthorityIdEditVo ownUserAssetAuthorityIdEditVo)
    {
        Long grantUserId = SecurityUtils.getUserId();

        amsOwnUserAssetAuthorityService.update(new UpdateWrapper<AmsOwnUserAssetAuthority>().
                set("status",ownUserAssetAuthorityIdEditVo.getStatus()).set("grant_user_id",grantUserId).
                eq("own_user_asset_authority_id",ownUserAssetAuthorityIdEditVo.getOwnUserAssetAuthorityId()));
        return toAjax(true);
    }

    @GetMapping("/adminGetAssetUserAuthList")
    @ApiOperation("管理员获取资产权限列表")
    public AjaxResult getAssetAuthList(){
        /** Long grantId = 18l; */
        Long deptId = SecurityUtils.getDeptId();

        List<ApplyUnlockAuthVo> applyInfos = amsOwnUserAssetAuthorityService.getApplyInfoByDeptId(deptId,1);

        List<Long> userIds = new LinkedList<>();
        for(ApplyUnlockAuthVo vo : applyInfos){
            userIds.add(vo.getUserId());
        }

        HashMap<Long, UserDeptName> data = userController.getUserNameDeptNameByUserId(userIds).getData();
        for(ApplyUnlockAuthVo vo : applyInfos){
            if(data != null && data.containsKey(vo.getUserId())){
                vo.setUserDeptName(data.get(vo.getUserId()).getDeptName());
                vo.setUserName(data.get(vo.getUserId()).getUserName());
            }
        }

        return AjaxResult.success(applyInfos);
    }
    @GetMapping("/adminGetUserApplyUnlockAuthList")
    @ApiOperation("管理员获取用户权限申请列表")
    public AjaxResult getAuthApplyList(){
        /** Long grantId = 18l; */
        Long deptId = SecurityUtils.getDeptId();

        List<ApplyUnlockAuthVo> applyInfos = amsOwnUserAssetAuthorityService.getApplyInfoByDeptId(deptId,-1);

        List<Long> userIds = new LinkedList<>();
        for(ApplyUnlockAuthVo vo : applyInfos){
            userIds.add(vo.getUserId());
        }

        HashMap<Long, UserDeptName> data = userController.getUserNameDeptNameByUserId(userIds).getData();
        for(ApplyUnlockAuthVo vo : applyInfos){
            if(data != null && data.containsKey(vo.getUserId())){
                vo.setUserDeptName(data.get(vo.getUserId()).getDeptName());
                vo.setUserName(data.get(vo.getUserId()).getUserName());
            }
        }

        return AjaxResult.success(applyInfos);
    }



    @GetMapping("/getAuthApplyHistoryList")
    @ApiOperation("用户获取自己的权限申请历史列表")
    public AjaxResult getAuthApplyHistoryList() {
//        List<ApplyHistoryInifo> infos = new LinkedList<>();
//        for (int i = 0; i < 5; i++) {
//            ApplyHistoryInifo info = new ApplyHistoryInifo();
//            info.setAssetAddress("达州市嘉陵区文理学院老校区东门旁");
//            info.setStartTime(1635392392000l);
//            info.setEndTime(1635392392000l);
//            info.setOwnUserAssetAuthorityId(new Long(i));
//            infos.add(info);
//        }
         Long userId = SecurityUtils.getUserId();
        /**Long userId = 23l; */
        List<ApplyHistoryInifo> infos = amsOwnUserAssetAuthorityService.getApplyHistoryInfos(userId);

        return AjaxResult.success(infos);

    }


    /**
     * 删除物联网资产设备用户权限信息
     */
    @PreAuthorize
    //@PreAuthorize(hasPermi = "ams:AmsOwnUserAssetAuthority:remove")
    @Log(title = "物联网资产设备用户权限信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ownUserAssetAuthorityIds}")
    public AjaxResult remove(@PathVariable Long[] ownUserAssetAuthorityIds) {
        return toAjax(amsOwnUserAssetAuthorityService.deleteAmsOwnUserAssetAuthorityByOwnUserAssetAuthorityIds(ownUserAssetAuthorityIds));
    }
}
